﻿using AppManager.Model;
using System.Runtime.Remoting.Messaging;
using System;
using AppManager.DomainModel;
using AutoMapper;
using Api.Common;
using AppManager.IBLL;

namespace AppManager.BLL
{
    public class Sys_UserService : BaseService<Sys_User>, IUserService
    {
        /// <summary>
        /// 两个current都有用，如果调用些公共方法时，可以使用父类的Current
        /// </summary>
        public new static Sys_UserService Current
        {
            get
            {
                var name = typeof(Sys_UserService).Name;
                var bll = CallContext.GetData(name) as Sys_UserService;
                if (bll != null)
                {
                    return bll;
                }
                bll = new Sys_UserService();
                CallContext.SetData(name, bll);
                return bll;
            }
        }

        /// <summary>
        /// 修改时只修改用户的LoginName和Name不修改密码
        /// 将领域模型和所有的业务写到bll层中
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddOrUpdateUser(Sys_UserEidtModel model)
        {
            var user = GetModel(s => s.Id == model.Id);
            if (user == null)
            {
                user = new Sys_User();
                user = Mapper.Map<Sys_User>(model);
            }
            else
            {
                user.LoginName = model.LoginName;
                user.Name = model.Name;
            }
            return AddOrUpdate(user);
        }

        public Sys_UserEidtModel GetModel(int? id)
        {
            if (id == null)
            {
                throw new MsgEx("user not exist");
            }

            var user = GetModel(s => s.Id == id.Value);
            if (user == null)
            {
                throw new MsgEx("user not exist");
            }

            var model = Mapper.Map<Sys_UserEidtModel>(user);
            return model;
        }
    }
}
